//控制提醒等待区域margin高度------------------
var wh=window.screen.availHeight;
var marginheight=(wh-80)/2;
$("#waitplace>div").css("marginTop",marginheight+"px");
var id=$.cookie("MYID");
//环信建立连接
var conn = new WebIM.connection({
    https: WebIM.config.https,
    url: WebIM.config.xmppURL,
    isAutoLogin: WebIM.config.isAutoLogin,
    isMultiLoginSessions: WebIM.config.isMultiLoginSessions
});
//登录
var options = {
    apiUrl: WebIM.config.apiURL,
    user:id,
    pwd:id,
    appKey: "pulu#pulu"
};
conn.open(options);
//跳转至群聊页面---------------------------------------------
function gotoallchat(e){
    location.href="chatingallpeople.html?roomid="+allroomid[e.dataset.num]+"&master="+e.dataset.master;
    $.cookie("allchatname",chatname[e.dataset.num]);
}
//添加回调函数 获取群组列表---------------------------------
var chatname=[];//群聊名称
var allroomid=[];//群聊roomid
var roomnum=0;
conn.listen({
    onOpened: function ( message ) {          //连接成功回调
        // 列出所有群组------------------------------------
        console.log(message);
        var option = {
            success: function (rooms) {
                console.log(rooms);
                //如果有就加载群聊组
                if(rooms&&rooms.length>0){
                    roomnum=rooms.length;
                }
            },
            error: function () {
                console.log('List groups error');
            }
        };
        conn.listRooms(option);
    },
    onClosed: function ( message ) {console.log(message);},         //连接关闭回调
    onTextMessage: function ( message ) {console.log(message);},    //收到文本消息
    onEmojiMessage: function ( message ) {console.log(message);},   //收到表情消息
    onPictureMessage: function ( message ) {console.log(message);}, //收到图片消息
    onCmdMessage: function ( message ) {console.log(message);},     //收到命令消息
    onAudioMessage: function ( message ) {console.log(message);},   //收到音频消息
    onLocationMessage: function ( message ) {console.log(message);},//收到位置消息
    onFileMessage: function ( message ) {console.log(message);},    //收到文件消息
    onVideoMessage: function (message) {console.log(message);},     //收到视频消息
    onPresence: function ( message ) {console.log(message);},       //收到联系人订阅请求、处理群组、聊天室被踢解散等消息
    onRoster: function ( message ) {console.log(message);},         //处理好友申请
    onInviteMessage: function ( message ) {console.log(message);},  //处理群组邀请
    onOnline: function (message) {console.log(message);},                  //本机网络连接成功
    onOffline: function (message) {console.log(message);},                 //本机网络掉线
    onError: function ( message ) {console.log(message);},          //失败回调
    onBlacklistUpdate: function (list) {       //黑名单变动
                                               // 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
        console.log(list);
    }
});
//主页面返回键----------------------------------------------
$("#mainpagegobackbtn").click(function(){
    //location.href="chatpage.html";
    history.go(-1);
});
//主页面添加按钮展示好友列表页面-----------------------------
$("#addallchatbtn").click(function(){
    $("#imgchoicefriend").css("display","block");
    $("#mainpage").css("display","none");
});
//关闭好友列表页面------------------------------------------
$("#friendgobackbtn").click(function(){
    //$("#imgchoicefriend").css("display","none");
    //$("#mainpage").css("display","block");
	history.go(-1);
});
//加载好友列表----------------------------------------------
var friendarr;//保存所有好友数据
$.ajax({
    datatype:"json",
    type:"get",
    url:"http://42.62.66.198:9001/api/PuluGoodFriend/GetByUserId?userId="+id,
    success:function(d){
        console.log("好友列表");
        console.log(d);
        if(d.Data.length>0){
            //排序
            friendarr= d.Data;
            //function compare(property){
            //    return function(a,b){
            //        var value1 = pinyin.getCamelChars(a[property]);
            //        var value2 = pinyin.getCamelChars(b[property]);
            //        return value1.localeCompare(value2);
            //    }
            //}
            //friendarr.sort(compare("friendnick"));
            hasharr={};//判断字母是否存在
            for(var i=0;i<friendarr.length;i++){
                friendarr[this.index]=i;
                //如果昵称开头为汉字或英文字母
                var key=pinyin.getCamelChars(friendarr[i].friendnick[0]);
                if(key.match(/[a-z|A-Z]/)){
                    key=key.toLowerCase();
                    console.log(key);
                    if(!hasharr[pinyin.getCamelChars(friendarr[i].friendnick[0])]){
                        hasharr[pinyin.getCamelChars(friendarr[i].friendnick[0])]=i;
                    }
                    $("#maina").append("<div class='section_header section_header_gray "+key+"' data-num='"+i+"' style='display:none'> <span class='"+key+"'>"+key+"</span> </div><div class='friends' id='"+friendarr[i].friendId+"'> <input type='checkbox' class='addchatpeoplebtn'><div class='imageplace'><a href='otherpeoplepage.html?otherid="+friendarr[i].friendId+"'><img src='http://42.62.66.198:8003/"+friendarr[i].headimg+"' class='topic_photo_img'/> </a> </div> <div class='innerplace tc_text'>"+friendarr[i].friendnick+"</div> </div>");
                    $("#aa").append("<div class='section_header section_header_gray "+key+"' data-num='"+i+"' style='display:none'> <span class='"+key+"'>"+key+"</span> </div><div class='friends' id='"+friendarr[i].friendId+"'> <input type='checkbox' class='addchatpeoplebtn' data-fid='"+friendarr[i].friendId+"'><div class='imageplace'><a href='otherpeoplepage.html?otherid="+friendarr[i].friendId+"'><img src='http://42.62.66.198:8003/"+friendarr[i].headimg+"' class='topic_photo_img'/> </a> </div> <div class='innerplace tc_text'>"+friendarr[i].friendnick+"</div> </div>");
                }else{
                    $("#mainjinghao").css("display","block");
                    $("#mainjinghao").append("<div class='friends' id='"+friendarr[i].friendId+"'> <input type='checkbox' class='addchatpeoplebtn'><div class='imageplace'><a href='otherpeoplepage.html?otherid="+friendarr[i].friendId+"'><img src='http://42.62.66.198:8003/"+friendarr[i].headimg+"' class='topic_photo_img'/> </a> </div> <div class='innerplace tc_text'>"+friendarr[i].friendnick+"</div> </div>");
                    $("#jinghao").css("display","block");
                    $("#jinghao").append("<div class='friends' id='"+friendarr[i].friendId+"'> <input type='checkbox' class='addchatpeoplebtn' data-fid='"+friendarr[i].friendId+"'><div class='imageplace'><a href='otherpeoplepage.html?otherid="+friendarr[i].friendId+"'><img src='http://42.62.66.198:8003/"+friendarr[i].headimg+"' class='topic_photo_img'/> </a> </div> <div class='innerplace tc_text'>"+friendarr[i].friendnick+"</div> </div>");
                };
            }
            //console.log(hasharr);
            for(var key in hasharr){
                key=key.toLowerCase();
                $("#sd-imgchoicefriend .section_header.section_header_gray."+key).eq(0).css("display","block");
                $("#somesee .section_header.section_header_gray."+key).eq(0).css("display","block");
                $("#imgchoicefriend .section_header.section_header_gray."+key).eq(0).css("display","block");
                $("#somesee .section_header.section_header_gray."+key).eq(0).css("display","block");
            };
        }
    }
});
//右侧导航条点击跳转
//字母键
var englishbtn1=document.querySelectorAll(".rightnav1 div.zmbtn");//导航条跳转
var tonum1=0;
for(var en1=0;en1<englishbtn1.length;en1++){
    englishbtn1[en1].onclick=function(e){
        console.log("点击的是："+e.target.innerHTML);
        if($(".section_header.section_header_gray."+e.target.innerHTML).length>0){
            var engtitlenum=parseFloat(hasharr[e.target.innerHTML]);
            var divnum=parseFloat(document.querySelector(".section_header.section_header_gray."+e.target.innerHTML).dataset.num);
            var divheight=$(".friends").eq(0).height();
            var titleheight=$("div.section_header.section_header_gray").eq(0).height();
            heightdiv=titleheight*engtitlenum+divnum*divheight;
            $(window).scrollTop(heightdiv);
            console.log("页面跳转操作")
        }
    };
}
//搜索好友------------------------------------------------------
$("#csearchbtn1").click(function(){//搜索跳转
    var word=$("#csearchinput1").val();
    $("#aa").css("display","none");
    $("#a1 div").remove();
    if(friendarr&&friendarr.length>0&&$("#csearchinput1").val()){
        var word=$("#csearchinput1").val();
        for(var i=0;i<friendarr.length;i++){
            var friendnick="";
            friendnick=friendarr[i].friendnick;
            //如果好友列表中有搜索内容
            if(friendnick.match(word)){
                $("#a1").append("<div class='section_header section_header_gray' data-num='"+i+"' style='display:none'> </div><div class='friends' id='"+friendarr[i].friendId+"'> <input type='checkbox' class='addchatpeoplebtn' data-fid='"+friendarr[i].friendId+"'><div class='imageplace'><a href='otherpeoplepage.html?otherid="+friendarr[i].friendId+"'><img src='http://42.62.66.198:8003/"+friendarr[i].headimg+"' class='topic_photo_img'/> </a> </div> <div class='innerplace tc_text'>"+friendarr[i].friendnick+"</div> </div>");
            }
        }
        $("#a1").css("display","block");
    }
});
document.onkeydown=function(event){
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if(e && e.keyCode==13){ // enter 键
        var word=$("#csearchinput1").val();
        $("#aa").css("display","none");
        $("#a1 div").remove();
        if(friendarr&&friendarr.length>0&&$("#csearchinput1").val()){
            var word=$("#csearchinput1").val();
            for(var i=0;i<friendarr.length;i++){
                var friendnick="";
                friendnick=friendarr[i].friendnick;
                //如果好友列表中有搜索内容
                if(friendnick.match(word)){
                    $("#a1").append("<div class='section_header section_header_gray' data-num='"+i+"' style='display:none'> </div><div class='friends' id='"+friendarr[i].friendId+"'> <input type='checkbox' class='addchatpeoplebtn' data-fid='"+friendarr[i].friendId+"'><div class='imageplace'><a href='otherpeoplepage.html?otherid="+friendarr[i].friendId+"'><img src='http://42.62.66.198:8003/"+friendarr[i].headimg+"' class='topic_photo_img'/> </a> </div> <div class='innerplace tc_text'>"+friendarr[i].friendnick+"</div></div>");
                }
            }
            $("#a1").css("display","block");
        }
    }
};
//监听好友搜索输入框---------------------------------------------
$("#csearchinput1").bind('input propertychange',function(){
    if(!$("#csearchinput1").val()){
        $("#aa").css("display","block");
        $("#a1").css("display","none");
    }
});
//好友页确定按钮 展开群聊主题------------------------------------
//var allinput=document.querySelectorAll("#aa .addchatpeoplebtn");
//for(var r= 0,len=allinput.length;r<len;r++){
//    allinput[r].onclick=function(){
//        if(allinput[r].checked){}
//        var num=0;
//        for(var i= 0,leng=allinput.length;i<leng;i++){
//
//        }
//    }
//}
$("#imgchoicedFDokbtn1").click(function(){
    $("#imgchoicefriend").css("display","none");
    $("#allchattitlepage").css("display","block");
});
//监听主题输入框有没有输入控制 主题确定按钮----------------------
$("#titleinput").bind('input propertychange',function(){
    //有群聊主题
    if(document.getElementById("titleinput").value&&document.getElementById("titleinput").value.length>0&&!document.getElementById("titleinput").value.match(/^\s+$/g)){
        document.getElementById("titleok").className="header_action_buttons"; //确定按钮样式
    }else{
        document.getElementById("titleok").className="header_action_buttons  cannotclick";
    }
});
//主题输入页面返回按钮 展开好友选择页面-----------------------
$("#titlegobackbtn").click(function(){
    $("#allchattitlepage").css("display","none");
    $("#imgchoicefriend").css("display","block");
});
//创建群聊最后一步 点击确定 获取所有数据 创建群聊-------------
var canclick=1;//确定按钮点击状态 1可以点
$("#titleok").click(function(){
    //判断按钮状态
    if(document.getElementById("titleok").className=="header_action_buttons"&&canclick==1){
        console.log("点击按钮了");
        canclick=0;//已经点击过了为0；
        var friendlist=[];//选择的好友列表
        //获取所有选择的好友
        var allinput=document.querySelectorAll("#aa .addchatpeoplebtn");
        var createallchat = function () {
            console.log("点击了创建群聊");
            var option = {
                subject:document.getElementById("titleinput").value,                       // 群名称
                description: '',         // 群简介
                members: friendlist,               // 以数组的形式存储需要加群的好友ID
                optionsPublic: true,                        // 允许任何人加入
                optionsModerate: false,                     // 加入需审批
                optionsMembersOnly: false,                  // 不允许任何人主动加入
                optionsAllowInvites: false                  // 允许群人员邀请
            };
            conn.createGroup(option);
        };
        var tim=0;
        var hasfriend="no";
        for(var i= 0,r=allinput.length;i<r;i++){
            tim++;
            //如果选择了好友
            if(allinput[i].checked===true){
                hasfriend="yes";
                friendlist.push(allinput[i].dataset.fid);
            };
            if(tim==r){
                console.log("循环结束了");
                console.log("hasfriend",hasfriend);
                if(hasfriend==="yes"){
                    console.log(friendlist);
                    //alert("循环结束");
                    createallchat();
                    $("#waitplace").css("display","block");
                    //所有群组个数---------------------------------------------
                    function allroom(){
                        var option = {
                            success: function (rooms) {
                                console.log(rooms);
                                //如果有就加载群聊组
                                if(rooms.length>roomnum){
                                    location.href="allchat.html";
                                }else{
                                    allroom()
                                }
                            },
                            error: function () {
                                console.log('List groups error');
                            }
                        };
                        conn.listRooms(option);
                    };
                    allroom();
                }
                else{
                    alert("请选择好友");
                }
            }

        }
    }
});